﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;

namespace LambdaToSql.EntityModel
{
    [Serializable]
    [DataContract]
    internal abstract class UpdateEntity<T> : BaseEntity<T> where T : class, new()
    {
        #region Base

        /// <summary>
        /// 条件
        /// </summary>
        [DataMember]
        public StringBuilder Where { get; set; }

        /// <summary>
        /// sql 参数
        /// </summary>
        [DataMember]
        public List<LambdaToSql.EntityModel.DataParameter> Parameters { get; set; }

        /// <summary>
        /// 更新字段
        /// </summary>
        [DataMember]
        public List<string> Fields { get; set; }

        /// <summary>
        /// 忽略字段
        /// </summary>
        [DataMember]
        public List<string> IgnoreFields { get; set; }

        /// <summary>
        /// 更新包含字段
        /// </summary>
        [DataMember]
        public List<string> UpdateColumns { get; set; }

        /// <summary>
        /// 数据对象
        /// </summary>
        [DataMember]
        public object Obj { get; set; }

        #endregion

        #region GetStr

        /// <summary>
        /// 最终查询字符串 只读
        /// </summary>
        [DataMember]
        public string SqlStr
        {
            get
            {
                var sql = new StringBuilder();
                sql.Append("update " + this.TableName + " set");
                sql.Append(" " + this.FieldsStr);
                sql.Append(" " + this.WhereStr);

                return sql.ToString();
            }
        }

        /// <summary>
        /// 条件字符串 只读
        /// </summary>
        [DataMember]
        public string WhereStr
        {
            get
            {
                var result = "";
                if (!string.IsNullOrEmpty(this.Where.ToString()))
                {
                    result = " where " + this.Where;
                }
                return result;
            }
        }

        /// <summary>
        /// 查询字段字符串 只读
        /// </summary>
        [DataMember]
        public string FieldsStr
        {
            get
            {
                var result = "";
                if (this.Fields.Count > 0)
                {
                    result = string.Join(",", this.Fields);
                }
                return result;
            }
        }
        #endregion

        public UpdateEntity(LambdaToSql.EntityModel.DbContext context) : base(context)
        {
            this.Where = new StringBuilder();

            this.Parameters = new List<LambdaToSql.EntityModel.DataParameter>();
            this.Fields = new List<string>();
            this.IgnoreFields = new List<string>();
            this.UpdateColumns = new List<string>();
        }
    }
}
